package com.ruoyi.system.service.impl;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.system.domain.PlatCollege;
import com.ruoyi.system.domain.PlatCollegeExample;
import com.ruoyi.system.mapper.PlatCollegeMapper;
import com.ruoyi.system.mapper.PlatMajorMapper;
import com.ruoyi.system.mapper.PlatUserMapper;
import com.ruoyi.system.service.IPlatCollegeService;
import com.ruoyi.system.service.IPlatTokenService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 学院管理
 */
@Service
public class PlatCollegeServiceImpl extends PlatCommonServiceImpl implements IPlatCollegeService {

    @Autowired
    private PlatUserMapper platUserMapper;
    @Autowired
    private IPlatTokenService platTokenService;
    @Autowired
    private PlatCollegeMapper platCollegeMapper;
    @Autowired
    private PlatMajorMapper platMajorMapper;

    @Override
    public void addCollege(PlatCollege platCollege) {
        //校验名称是否重复
        PlatCollegeExample example = new PlatCollegeExample();
        PlatCollegeExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(platCollege.getName());
        List<PlatCollege> list = platCollegeMapper.selectByExample(example);
        if (platCollege.getId() != null && list.size() > 0 && !String.valueOf(list.get(0).getId()).equals(String.valueOf(platCollege.getId()))) {
            throw new BusinessException("学院名称已存在!");
        } else if (platCollege.getId() == null && list.size() > 0) {
            throw new BusinessException("学院名称已存在!");
        }

        if (platCollege.getId() != null) {
            platCollege.setUpdateTime(new Date());
            platCollegeMapper.updateByPrimaryKeySelective(platCollege);
            return;
        }
        platCollege.setCreateTime(new Date());
        platCollegeMapper.insert(platCollege);
    }

    @Override
    public List<PlatCollege> collegeList(PlatCollege platCollege) {
        PlatCollegeExample platCollegeExample = new PlatCollegeExample();
        platCollegeExample.setOrderByClause(orderByClause);
        if (!StringUtils.isEmpty(platCollege.getName())) {
            PlatCollegeExample.Criteria criteria = platCollegeExample.createCriteria();
            criteria.andNameLike(LIKE + platCollege.getName() + LIKE);
        }
        List<PlatCollege> list = platCollegeMapper.selectByExample(platCollegeExample);
        for (PlatCollege platCollegePO : list) {
            Integer num = platMajorMapper.selectCollegeNum(platCollegePO.getId());
            platCollegePO.setPlatMajorNum(num);
        }
        return list;
    }

    @Override
    public void delCollege(Long id) {
        platCollegeMapper.deleteByPrimaryKey(id);
    }
}
